//
//  ViewController.m
//  HondaPro_2
//
//  Created by Eric on 13-5-29.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "MainViewController.h"
#import "UserDefinedCell.h"
#import "MainMenuDataModel.h"
#import "SVProgressHUD.h"
#import "CarCalendarQueryViewController.h"
#import "HJRepairTurnCarController.h"
#import "HJRepairSettlementViewController.h"
#import "HJCustomerReceptionViewController.h"

#import "WaringInformationViewController.h"
#import "SearchPartsInventoryViewController.h"

#import "ServiceHomeViewController.h"
#import "LoginViewController.h"
#import "UIViewController+MJPopupViewController.h"
#import "SystemSetViewController.h"
#import "webConfig.h"
#import "webService.h"

#import "ManagementViewController.h"        //预约管理
#import "VehicleSettlementViewController.h"//验车结算
#import "InformationViewController.h"     //车主车辆信息
#import "ServiceAssignedViewController.h"//维修派工

#import "AddServiceViewController.h"//增值服务
#import "MyAFNetWorkManager.h"
#import "NetworkManager.h"

//#import "../HomePage/HomePage/HomePageController.h"
//#import "../HomePage/HomePage/StoreViewController.h"
//#import "../HomePage/HomePage/EnterHondaViewController.h"
//#import "../HomePage/HomePage/TechnologyViewController.h"
//#import "../HomePage/HomePage/BrandViewController.h"

#import "ConfigCodeHelper.h"
#import "MyAFNetWorkManager.h"

#define MM_CAI_DAN_SHOU_QI_PNG_                 @"菜单收起.png"
#define MM_CAI_DAN_XIA_LA_PNG_                  @"菜单展开.png"
#define MM_DAI_JIE_SUAN_PNG_                    @"待结算.png"
#define MM_WEI_XIU_ZHONG_PNG_                   @"维修中.png"
#define MM_YU_YUE_JIN_CHANG_PNG_                @"预约进厂.png"

//下拉菜单箭头的tag宏定义
#define MM_ARROW_TAG_               100

//宏定义btn的状态
#define BTN_IS_CURR_PERSON_         0
#define BTN_IS_ALL_PERSON_          1

#define kAlertMessage(aMessage) dispatch_async(dispatch_get_main_queue(), ^{\
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:aMessage delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil, nil];\
[alert show];\
});

@interface MainViewController ()
@property (assign, nonatomic) UIImageView  *needDownloadCountBgView;
@property (assign, nonatomic) UILabel *needDownloadCountLabel;
@property (nonatomic) int needDownloadCount;
@property (weak, nonatomic) IBOutlet UILabel *explainLabel;

@property(nonatomic,weak)IBOutlet UILabel *nameLab;
@property(nonatomic,weak)IBOutlet UIButton *yuyueBtn;
@property(nonatomic,weak)IBOutlet UIButton *weixiuBtn;
@property(nonatomic,weak)IBOutlet UIButton *jiesuanBtn;


@end

@implementation MainViewController
@synthesize settingView = _settingView;
+ (MainViewController *)sharedViewController {
    
    static MainViewController *s_sharedViewController = nil;
    
    @synchronized(s_sharedViewController){
        
        if (s_sharedViewController==nil || [s_sharedViewController isKindOfClass:self]) {
            
            s_sharedViewController = [[MainViewController alloc] initWithNibName:nil bundle:nil];
        }
        
    }
    return s_sharedViewController;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(carInfoShouldUpdate:) name:NotificationCarInfoShouldUpdate object:nil];

                        //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDecompressComplete:) name:Decompress_Complete object:nil];
    }
    return self;
}
- (void)carInfoShouldUpdate:(NSNotification*)notify {
    [self performSelectorOnMainThread:@selector(carInfoShouldUpdateOnMainThread) withObject:nil waitUntilDone:NO];
}
- (void)carInfoShouldUpdateOnMainThread{
    self.needDownloadCountBgView.hidden = NO;
    self.needDownloadCount++;
    self.needDownloadCountLabel.text = [NSString stringWithFormat:@"%d", self.needDownloadCount];
}

-(BOOL)prefersStatusBarHidden{
    return YES;
}
//获取数据字典
-(void)getDataDictionary
{
    //QUERY_DIC_FOR_SALES_PAD
    NSString   *actionLogin=[NSString stringWithFormat:@"QUERY_DIC_FOR_SALES_PAD"];
    
    //_WEAK_SELF
    [[NetworkingViewController sharedController] showNetworkingWithTitle:nil content:@"查询中，请稍后..." activiting:YES enableDismiss:NO];
    
    [MyAFNetWorkManager postWithParam:nil andAction:actionLogin finish:^(NSData *data, NSDictionary *obj, NSError *error)
     {
         [[NetworkingViewController sharedController] dismissNetworking];
         if (error == nil)
         {
             NSDictionary  *returnDic=(NSDictionary *)obj;
             NSLog(@"全部数据字典：%@",returnDic);
             [[NetworkingViewController sharedController] showNetworkingWithTitle:@"数据更新成功！" content:nil activiting:NO enableDismiss:NO];
             [[NetworkingViewController sharedController] performSelector:@selector(dismissNetworking) withObject:nil afterDelay:1.5];
             NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
             NSString *paths=[[path objectAtIndex:0] stringByAppendingPathComponent:@"Dic.text"];
             [returnDic writeToFile:paths atomically:YES];
             
         }
         else
         {
             NSLog(@"%@",error);
         }
     }];
    
    
}

#pragma mark - study json parse

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    ////此获取的版本号对应version，打印出来对应为1.2.3.4.5这样的字符串
    NSString *string = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    self.explainLabel.text=[self.explainLabel.text stringByAppendingString:string];
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
    [self.navigationController.navigationBar setHidden:YES];
    
    [self addAllObserver];
    
    //[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(zhuxiaodenglu) name:@"zhuxiaodenglu" object:nil];
    //[[NSNotificationCenter defaultCenter] removeObserver:self name:@"zhuxiaodenglu" object:nil];
    //    MainMenuDataModel *ins = [MainMenuDataModel sharedMainMenuDataModel];
    //    [ins jsonWrittenToFile];
    //    [ins jsonParseFromFile];
    
//    [self loadViewbuttonht];
    
    _tbView = (UITableView *)[self.view viewWithTag:10];
    //初始化刷新控件
    if (nil == _refreshTableView)
    {
        CGRect rect = CGRectMake(0.0f, 0.0f-_tbView.bounds.size.height, _tbView.bounds.size.width, _tbView.bounds.size.height);
        _refreshTableView = [[EGORefreshTableHeaderView alloc] initWithFrame:rect];
        _refreshTableView.delegate = self;
        [_tbView addSubview:_refreshTableView];
    }
    [_tbView reloadData];
    
    //创建tableView的标题View
    [self createTableHeadView];
    
    //判断是否登陆
    
    [self performSelector:@selector(systemLogin) withObject:nil afterDelay:0.3f];
    
//    //请求工作台数据
    NSDate *dates = [NSDate date];
    NSDateFormatter *format=[[NSDateFormatter alloc]init];
    [format setDateFormat:@"yyyy-MM-dd"];
    NSMutableArray *paras=[NSMutableArray arrayWithObjects:@"date",[format stringFromDate:dates], nil];
    [HelpClass getWebServiceDataByString:REPAIRWORKLIST andArrObject:paras];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connetLogin) name:@"connetLogin" object:nil];
    
    [_yuyueBtn addTarget:self action:@selector(queryButton:) forControlEvents:UIControlEventTouchUpInside];
    [_weixiuBtn addTarget:self action:@selector(gotoRepairSettlement) forControlEvents:UIControlEventTouchUpInside];
    [_jiesuanBtn addTarget:self action:@selector(gotoRepairCar) forControlEvents:UIControlEventTouchUpInside];
    
}
-(void)gotoRepairSettlement{
    VehicleSettlementViewController *vsv = [[VehicleSettlementViewController alloc]initWithNibName:@"VehicleSettlementViewController" bundle:nil];
    [self.navigationController pushViewController:vsv animated:YES];
}
-(void)gotoRepairCar{
    HJRepairTurnCarController*vc=[HJRepairTurnCarController new];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //初始化车牌号
    [MainMenuDataModel sharedMainMenuDataModel].strCurrentPlateNumber = @"";
    
    //QUERY_REPAIR_WORK_COUNT
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
//    //remove observer
//    [self removeAllObserver];
    
}

-(void)refreshData:(NSNotification*)notification{
    
    
    _nameLab.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"USER_NAME"];
    
    
    [MyAFNetWorkManager postWithParam:nil andAction:@"QUERY_REPAIR_WORK_COUNT" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        
        if (!error) {
            NSLog(@"工作台数据:%@",obj);
//            NSArray *yuyue = [obj objectForKey:@"BOOKING_ORDER_COUNT"];
//            NSDictionary *yuyueDic = yuyue[0];
            NSString *yuyueTotal = obj[@"BOOKING_COUNT"];
            NSString *yuyueToday = obj[@"IN_ASC_COUNT"];
            
            NSArray *other = [obj objectForKey:@"REPAIR_ORDER_COUNT"];
            
            NSDictionary *otherDic = other[0];
            
            NSNumber *settleTotal = otherDic[@"DISPATCH"];
            
//            NSNumber *repairToday = otherDic[@"NOT_COMPLETE"];
            
            NSNumber *balanceTotal = otherDic[@"COMPLETE"];
            
//            NSNumber *balanceToday = otherDic[@"BALANCE"];
            
            [_yuyueBtn setTitle:[NSString stringWithFormat:@"%@/%@",yuyueToday,yuyueTotal] forState:UIControlStateNormal];
            
            [_weixiuBtn setTitle:[NSString stringWithFormat:@"%@",settleTotal] forState:UIControlStateNormal];
            
            [_jiesuanBtn setTitle:[NSString stringWithFormat:@"%@",balanceTotal] forState:UIControlStateNormal];
        }
        else{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        }
        
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger nRowSum = 0;
    
    switch (section)
    {
        case 0:
            nRowSum = [_arrCurrentPrecontractList count];
            break;
        case 1:
            nRowSum = [_arrCurrentMaintenanceList count];
            break;
        case 2:
            nRowSum = [_arrCurrentSettlementList count];
            break;
            
        default:
            break;
    }
    
    HeadView* headView = [_headViewDis objectAtIndex:section];
    
    return (YES == headView.open ? nRowSum : 0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[UserDefinedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    // Configure the cell...
    
    NSInteger section = [indexPath section];
    NSInteger row = [indexPath row];
    
    //初始化cell上的字体和颜色
    [self setUpFontAndColorForWorkBoardByCell:cell];
    cell.backgroundColor = [UIColor clearColor];
    //cell的风格是：浅浅灰色和浅灰色间隔出现，第一行是浅灰色
//    switch (row%2)
//    {
//        case 0:
//            //浅灰色
//            cell.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
//            break;
//        case 1:
//            //浅浅灰色
//            cell.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1];
//            break;
//            
//        default:
//            break;
//    }
    
    switch (section)
    {
        case 0:
        {
            /*
             车牌号、客户姓名
             类型、电话
             预约时间
             {
             "plateNumber": "12322",
             "precontractTime": " 13:46",
             "repairTypeName": "一般修理",
             "customerName": "马先生",
             "evaluatorPersonId": "2181",
             "evaluatorPersonName": "2",
             "mobile": "1235778"
             }
             */
            NSDictionary *dic = [_arrCurrentPrecontractList objectAtIndex:row];
            ((UILabel *)[cell viewWithTag:1]).text = [NSString stringWithFormat:@"\t%@",[dic objectForKey:@"plateNumber"]];
            ((UILabel *)[cell viewWithTag:2]).text = [NSString stringWithFormat:@"客户：%@",[dic objectForKey:@"customerName"]];
            ((UILabel *)[cell viewWithTag:3]).text = [NSString stringWithFormat:@"\t接待员：%@",[dic objectForKey:@"evaluatorPersonName"]];
            ((UILabel *)[cell viewWithTag:4]).text = [dic objectForKey:@"mobile"];
            ((UILabel *)[cell viewWithTag:5]).text = [NSString stringWithFormat:@"\t%@\t\t预约时间：%@",[dic objectForKey:@"repairTypeName"],[dic objectForKey:@"precontractTime"]];
            
            //设置cell的背景色
            [self setUpPrecontractDisByCell:cell inRow:row];
        }
            break;
        case 1:
        {
            /*
             车牌号
             估价人、作业单状态
             预计交车时间
             {
             "plateNumber": "苏DS6088*",
             "customerName": "吴实清",
             "deliveryPlannedDate": "9999-12-31 23:59",
             "evaluatorPersonId": "95",
             "evaluatorPersonName": "盛榴萍",
             "stateName": "返完工",
             "currentStation": "",
             "mobile": "13946110619"
             }
             */
            NSDictionary *dic = [_arrCurrentMaintenanceList objectAtIndex:row];
            ((UILabel *)[cell viewWithTag:1]).text = [NSString stringWithFormat:@"\t%@",[dic objectForKey:@"plateNumber"]];
            ((UILabel *)[cell viewWithTag:2]).text = [dic objectForKey:@""];
            ((UILabel *)[cell viewWithTag:3]).text = [NSString stringWithFormat:@"\t估价人：%@",[dic objectForKey:@"evaluatorPersonName"]];
            ((UILabel *)[cell viewWithTag:4]).text = [dic objectForKey:@"stateName"];
            ((UILabel *)[cell viewWithTag:5]).text = [NSString stringWithFormat:@"\t预计交车时间：%@",[dic objectForKey:@"deliveryPlannedDate"]];
            
            //设置cell的背景色
            [self setUpMantenceDisByCell:cell inRow:row];
        }
            break;
        case 2:
        {
            /*
             车牌号、接待员
             客户姓名、客户电话
             预计交车时间
             {
             "deliveryPlannedDate": "2013-02-25 15:30",
             "plateNumber": "苏DZP276",
             "customerName": "徐周平",
             "evaluatorPersonId": "1841",
             "evaluatorPersonName": "沈黎明",
             "mobile": "13853560897"
             }
             */
            NSDictionary *dic = [_arrCurrentSettlementList objectAtIndex:row];
            ((UILabel *)[cell viewWithTag:1]).text = [NSString stringWithFormat:@"\t%@",[dic objectForKey:@"plateNumber"]];
            ((UILabel *)[cell viewWithTag:2]).text = [NSString stringWithFormat:@"接待员：%@",[dic objectForKey:@"evaluatorPersonName"]];
            ((UILabel *)[cell viewWithTag:3]).text = [NSString stringWithFormat:@"\t客户：%@",[dic objectForKey:@"customerName"]];
            ((UILabel *)[cell viewWithTag:4]).text = [dic objectForKey:@"mobile"];
            ((UILabel *)[cell viewWithTag:5]).text = [NSString stringWithFormat:@"\t预计交车时间：%@",[dic objectForKey:@"deliveryPlannedDate"]];
            
            //设置cell的背景色
            [self setUpSettlementDisByCell:cell inRow:row];
        }
            break;
            
        default:
            break;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 56;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (1 != [indexPath section])
//    {
//        return 56+25;
//    }
//    return 56;
    
    return 56+25;
}

//-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    switch (section)
//    {
//        case 0:
//            return @"预约进场";
//        case 1:
//            return @"维修中";
//        case 2:
//            return @"待结算";
//            
//        default:
//            break;
//    }
//    return @"xxxxx";
//}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [_headViewDis objectAtIndex:section];
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = [indexPath section];
    NSInteger row = [indexPath row];
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    switch (section)
    {
        case 0:
            modelIns.strCurrentPlateNumber = [[_arrCurrentPrecontractList objectAtIndex:row] objectForKey:@"plateNumber"];
            [self switchToPreContractUIByPlateNumber:modelIns.strCurrentPlateNumber];
            break;
        case 1:
            modelIns.strCurrentPlateNumber = [[_arrCurrentMaintenanceList objectAtIndex:row] objectForKey:@"plateNumber"];
            //进入服务接待主页
            [self switchToServiceUIByPlateNumber:modelIns.strCurrentPlateNumber];
            break;
        case 2:
            modelIns.strCurrentPlateNumber = [[_arrCurrentSettlementList objectAtIndex:row] objectForKey:@"plateNumber"];
            [self switchToSettlementUIByPlateNumber:modelIns.strCurrentPlateNumber];
            break;
            
        default:
            break;
    }
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods
//开始重新加载时调用的方法
- (void)reloadTableViewDataSource{
	_reloading = YES;
    
    webService *web=[[webService alloc] init];
    web.methodName = REPAIRWORKLIST;
    
    NSDate *dates = [NSDate date];
    NSDateFormatter *format=[[NSDateFormatter alloc]init];
    [format setDateFormat:@"yyyy-MM-dd"];
    NSMutableArray *paras=[NSMutableArray arrayWithObjects:@"date",[format stringFromDate:dates], nil];
    [web commonGetSharedRequest:REPAIRWORKLIST wsparas:paras];
    
    //开始刷新后执行后台线程，在此之前可以开启HUD或其他对UI进行阻塞
    [NSThread detachNewThreadSelector:@selector(doInBackground) toTarget:self withObject:nil];
}

//完成加载时调用的方法
- (void)doneLoadingTableViewData{
 
	_reloading = NO;
	[_refreshTableView egoRefreshScrollViewDataSourceDidFinishedLoading:_tbView];
    
    //刷新表格内容
    [_tbView reloadData];
}

#pragma mark -
#pragma mark Background operation
//这个方法运行于子线程中，完成获取刷新数据的操作
-(void)doInBackground
{
//    NSLog(@"doInBackground");
    

    [NSThread sleepForTimeInterval:2];
    
  
    //在刷新表格内容之前获取新的数据
    /*郭另朝注释
    NSMutableDictionary *theTmpDic1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"粤Axxx",@"plateNumber",@"10:35",@"precontractTime",@"一般修理",@"repairTypeName", nil];
    NSMutableDictionary *theTmpDic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"粤Axxx",@"plateNumber",@"10:40",@"precontractTime",@"一般修理",@"repairTypeName", nil];
    NSMutableDictionary *theTmpDic3 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"粤Axxx",@"plateNumber",@"10:45",@"precontractTime",@"一般修理",@"repairTypeName", nil];
    NSMutableArray *theTmpArr = [NSMutableArray arrayWithObjects:theTmpDic1,theTmpDic2,theTmpDic3, nil];
    [MainMenuDataModel sharedMainMenuDataModel].precontractList = [NSArray arrayWithArray:theTmpArr];
    
    [[MainMenuDataModel sharedMainMenuDataModel] printData];
     */
    /*end of just for test*/
    
    //后台操作线程执行完后，到主线程更新UI
    [self performSelectorOnMainThread:@selector(doneLoadingTableViewData) withObject:nil waitUntilDone:YES];
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods
//下拉被触发调用的委托方法
-(void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view
{
    [self reloadTableViewDataSource];
}

//返回当前是刷新还是无刷新状态
-(BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view
{
    return _reloading;
}

//返回刷新时间的回调方法
-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view
{
    return [NSDate date];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods
//滚动控件的委托方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_refreshTableView egoRefreshScrollViewDidScroll:scrollView];
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [_refreshTableView egoRefreshScrollViewDidEndDragging:scrollView];
}

#pragma mark - 按钮回调函数

- (IBAction)carCalendarQueryBtnPressed:(UIButton *)sender
{
//    NSLog(@"carCalendarQueryBtnPressed!!!");
    
//    //进行界面跳转
//   CarCalendarQueryViewController *vc = [[CarCalendarQueryViewController alloc] initWithNibName:@"CarCalendarQueryViewController" bundle:nil];
//    [self presentModalViewController:vc animated:YES];
}

//跳转到三包信息查询界面
- (IBAction)waringInformationBtnPressed:(UIButton *)sender
{
//    NSLog(@"waringInformationBtnPressed!!!");
    
    //进行界面跳转
    WaringInformationViewController *vc = [[WaringInformationViewController alloc] initWithNibName:@"WaringInformationViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

//跳转到零件库查询界面
- (IBAction)searchPartsInventoryBtnPressed:(UIButton *)sender
{

    SearchPartsInventoryViewController *vc = [[SearchPartsInventoryViewController alloc] initWithNibName:@"SearchPartsInventoryViewController" bundle:nil];
//    [self presentViewController:vc animated:YES completion:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -郭另朝 服务接待

-(IBAction)serviceSelectBtn:(id)sender{
    
    
    //进入服务接待主页
    HJCustomerReceptionViewController*vc=[HJCustomerReceptionViewController new];
    [self.navigationController pushViewController:vc animated:YES];
//    ServiceHomeViewController *VCon = [[ServiceHomeViewController alloc] initWithNibName:@"ServiceHomeViewController" bundle:nil];
//    [self.navigationController pushViewController:VCon animated:YES];
//    
    //[self presentViewController:VCon animated:YES completion:nil];
}
- (void)systemLogin {
    
    self.logCon = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
    
    self.logCon.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentViewController:self.logCon animated:YES completion:nil];
}

- (void)connetLogin
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:4];
    [dic setValue:[user objectForKey:@"ENTITY_CODE"]?:@"IF990000" forKey:@"ENTITY_CODE"];
    [dic setValue:[user objectForKey:@"userName"] forKey:@"USER_CODE"];
    [dic setValue:[user objectForKey:@"passWord"] forKey:@"PASSWORD"];
    [dic setValue:@"12781001" forKey:@"PAD_LOGIN"];
    
    [MyAFNetWorkManager postWithParam:dic andAction:@"LOGIN_ASC" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        if (error == nil)
        {
            [SVProgressHUD dismiss];
            NSDictionary *dic = obj;
            NSLog(@"登录接口： %@",obj);
            if([[dic valueForKey:@"SUCCESS"]integerValue]==1)
            {
                
                NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
                
                [user setObject:[dic valueForKey:@"USER_ID" ] forKey:@"userId"];
                //                    [user setObject:self.ENTITY_CODE forKey:@"ENTITY_CODE"];
                //                    [user setObject:self.ENTITY_NAME forKey:@"ENTITY_NAME"];
                [user setObject:@"YES" forKey:@"IsLoginSuccess"];
                [user synchronize];
                
                [self getDataDictionary];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"QUERY_REPAIR_WORK_COUNT" object:nil];
                [self dismissViewControllerAnimated:YES completion:nil];
            }
            else{
                kAlertMessage(obj[@"MSG"]);
            }
            
        }
        else{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        }
        
    }];
}

//-(void)zhuxiaodenglu
//{
//    webService *web=[[webService alloc] init];
//    web.methodName = LOGOUT;
//    [web commonGetSharedRequest:LOGOUT wsparas:nil];
//
//    self.logCon = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
//    
//    self.logCon.modalPresentationStyle = UIModalPresentationFormSheet;
//  [self presentViewController:self.logCon animated:YES completion:nil];
//
//}
//zhuxiaodelegate
-(void)iszhuxiao:(NSString *)iszhuxiao
{
    [_settingView removeFromSuperview];

    if([iszhuxiao isEqualToString:@"IS"])
    {
//        webService *web=[[webService alloc] init];
//            web.methodName = LOGOUT;
//            [web commonGetSharedRequest:LOGOUT wsparas:nil];
        [[NetworkingViewController sharedController] showNetworkingWithTitle:@"注销成功" content:nil activiting:NO enableDismiss:YES];
            self.logCon = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        
            self.logCon.modalPresentationStyle = UIModalPresentationFormSheet;
          [self presentViewController:self.logCon animated:YES completion:nil];
        
        [[NetworkingViewController sharedController] dismissNetworking];
    }
}
-(void)logBack:(id)sender{
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.4];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    
    [self.logCon.view setFrame:CGRectMake(0, 678, 1024, 768)];
    [UIView commitAnimations];
    [self.logCon.view removeFromSuperview];
}

#pragma mark -胡涛 预约查询   验车结算  车主车辆信息  维修派工
-(void)loadViewbuttonht
{
    UIButton *queryButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [queryButton setBackgroundColor:[UIColor clearColor]];
    [queryButton setFrame:CGRectMake(560, 63, 257, 161)];
    [queryButton addTarget:self action:@selector(queryButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:queryButton];
    
    UIButton *settlementButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [settlementButton setBackgroundColor:[UIColor clearColor]];
    [settlementButton setFrame:CGRectMake(301, 393, 257, 161)];
    [settlementButton addTarget:self action:@selector(settlementButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:settlementButton];
    
    UIButton *ownerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [ownerButton setBackgroundColor:[UIColor clearColor]];
    [ownerButton setFrame:CGRectMake(561, 229, 257, 161)];
    [ownerButton addTarget:self action:@selector(ownerButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:ownerButton];
    
    UIButton *ServiceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [ServiceButton setBackgroundColor:[UIColor clearColor]];
    [ServiceButton setFrame:CGRectMake(304, 230, 257, 161)];
    [ServiceButton addTarget:self action:@selector(ServiceButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:ServiceButton];
}

-(IBAction)queryButton:(id)sender
{
    ManagementViewController *mnv = [[ManagementViewController alloc]initWithNibName:@"ManagementViewController" bundle:nil];
    [self.navigationController pushViewController:mnv animated:YES];
    
}
-(IBAction)settlementButton:(id)sender
{
    
    VehicleSettlementViewController *vsv = [[VehicleSettlementViewController alloc]initWithNibName:@"VehicleSettlementViewController" bundle:nil];
    [self.navigationController pushViewController:vsv animated:YES];
}
-(IBAction)pass:(id)sender
{
    VehicleSettlementViewController *vsv = [[VehicleSettlementViewController alloc]initWithNibName:@"VehicleSettlementViewController" bundle:nil];
    [self.navigationController pushViewController:vsv animated:YES];
}
-(IBAction)ownerButton:(id)sender
{
    InformationViewController *ivv = [[InformationViewController alloc]initWithNibName:@"InformationViewController" bundle:nil];
    [self.navigationController pushViewController:ivv animated:YES];
}

//维修派工
-(IBAction)ServiceButton:(id)sender
{
    ServiceAssignedViewController *ivv = [[ServiceAssignedViewController alloc]initWithNibName:@"ServiceAssignedViewController" bundle:nil];
    [self.navigationController pushViewController:ivv animated:YES];
}

//增值服务
- (IBAction)addServiceSelect:(id)sender {
    HJRepairTurnCarController*vc=[HJRepairTurnCarController new];
    [self.navigationController pushViewController:vc animated:YES];
//   AddServiceViewController* viewController = [[AddServiceViewController alloc] initWithNibName:@"AddServiceViewController" bundle:nil];
//    viewController.detailType = TypeZengzhi;
//   [self.navigationController pushViewController:viewController animated:YES];
}

/*add by mm*/
-(void)createTableHeadView
{
    _currentRow = -1;
    _headViewDis = [[NSMutableArray alloc]init ];
    
    NSArray *arrPngName = @[@"work1",@"work2",@"work3",];
    NSArray *arrTitle = @[@"预约进场",@"维修中",@"点结算",];
    
    for(int i = 0;i< 3 ;i++)
	{
		HeadView* headview = [[HeadView alloc] init];
        headview.delegate = self;
		headview.section = i;
        if (0 == i)
        {
            headview.open = YES;
        }
        else
        {
            headview.open = NO;
        }
//        [headview.backBtn setBackgroundImage:[UIImage imageNamed:[arrPngName objectAtIndex:i]] forState:UIControlStateNormal];
        [headview.backBtn setImage:[UIImage imageNamed:arrPngName[i]] forState:UIControlStateNormal];
        [headview.backBtn setTitle:arrTitle[i] forState:UIControlStateNormal];
        [self createArrowOnBtnByState:headview.open OnHeadView:headview];
		[_headViewDis addObject:headview];
        
        if (0 == i)
        {
            //给View上添加一个Button
            _button1ForWorkBoard = [UIButton buttonWithType:UIButtonTypeCustom];
            [_button1ForWorkBoard setFrame:CGRectMake(140, 12, 120, 35)];
            [_button1ForWorkBoard setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            _button1ForWorkBoard.titleLabel.font = [UIFont systemFontOfSize:13];
            [_button1ForWorkBoard setBackgroundImage:[UIImage imageNamed:@"work-kuan"] forState:UIControlStateNormal];
            [_button1ForWorkBoard addTarget:self action:@selector(BtnOnHeadViewPressed:) forControlEvents:UIControlEventTouchUpInside];
            [headview addSubview:_button1ForWorkBoard];
            
            //设置按钮的状态
            _bFlagBtn1ForWorkBoard = BTN_IS_CURR_PERSON_;
        }
        else if (1 == i)
        {
            //给View上添加一个Button
            _button2ForWorkBoard = [UIButton buttonWithType:UIButtonTypeCustom];
            [_button2ForWorkBoard setFrame:CGRectMake(140, 12, 120, 35)];
            [_button2ForWorkBoard setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            _button2ForWorkBoard.titleLabel.font = [UIFont systemFontOfSize:13];
            [_button2ForWorkBoard setBackgroundImage:[UIImage imageNamed:@"work-kuan"] forState:UIControlStateNormal];
            [_button2ForWorkBoard addTarget:self action:@selector(BtnOnHeadViewPressed:) forControlEvents:UIControlEventTouchUpInside];
            [headview addSubview:_button2ForWorkBoard];
            
            //设置按钮的状态
            _bFlagBtn2ForWorkBoard = BTN_IS_CURR_PERSON_;
        }
        else if (2 == i)
        {
            //给View上添加一个Button
            _button3ForWorkBoard = [UIButton buttonWithType:UIButtonTypeCustom];
            [_button3ForWorkBoard setFrame:CGRectMake(140, 12, 120, 35)];
            [_button3ForWorkBoard setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            _button3ForWorkBoard.titleLabel.font = [UIFont systemFontOfSize:13];
            [_button3ForWorkBoard setBackgroundImage:[UIImage imageNamed:@"work-kuan"] forState:UIControlStateNormal];
            [_button3ForWorkBoard addTarget:self action:@selector(BtnOnHeadViewPressed:) forControlEvents:UIControlEventTouchUpInside];
            [headview addSubview:_button3ForWorkBoard];
            
            //设置按钮的状态
            _bFlagBtn3ForWorkBoard = BTN_IS_CURR_PERSON_;
        }
    }
    
    //设置数据
    [self setUpArrValByBtnState];
    [self setUpBtnDisStr];
}

-(void)resetTableView
{
    for(int i = 0;i<[_headViewDis count];i++)
    {
        HeadView *head = [_headViewDis objectAtIndex:i];
        
        if(head.section == _currentSection)
        {
            head.open = YES;
        }
        else
        {
            head.open = NO;
        }
        
        [self createArrowOnBtnByState:head.open OnHeadView:head];
        
    }
    [_tbView reloadData];
}

-(void)createArrowOnBtnByState:(BOOL)state OnHeadView:(HeadView *)view
{
//    //进来不管3 7 21 先remove掉已有的箭头
//    [[view.backBtn viewWithTag:MM_ARROW_TAG_] removeFromSuperview];
//    
//    if (YES == state)
//    {
//        //添加下拉展开箭头
//        UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:MM_CAI_DAN_XIA_LA_PNG_]];
//        imgView.frame = CGRectMake(view.frame.size.width-30, 15, 20, 20);
//        imgView.tag = MM_ARROW_TAG_;
//        [view addSubview:imgView];
//    }
//    else
//    {
//        //添加下拉收起箭头
//        UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:MM_CAI_DAN_SHOU_QI_PNG_]];
//        imgView.frame = CGRectMake(view.frame.size.width-30, 15, 20, 20);
//        imgView.tag = MM_ARROW_TAG_;
//        [view addSubview:imgView];
//    }
}

-(void)setUpFontAndColorForWorkBoardByCell:(UITableViewCell *)xingCanCell;
{
    for (int i = 1; i<=5; i++)
    {
        UILabel *lbl = ((UILabel *)[xingCanCell viewWithTag:i]);
        lbl.backgroundColor = [UIColor clearColor];
        lbl.textColor = [UIColor darkGrayColor];
        lbl.font = [UIFont systemFontOfSize:13];
    }
}

-(void)setUpPrecontractDisByCell:(UITableViewCell *)xingCanCell inRow:(NSInteger)xingCanRow
{
    //如果 预约进厂 的预约时间在 半小时以内则标注其cell的背景色为黄色
    NSArray *arrPrecontractListTmp = _arrCurrentPrecontractList;
    
    NSString *strTmp = [[arrPrecontractListTmp objectAtIndex:xingCanRow] objectForKey:@"precontractTime"];
    
    NSTimeInterval precontractTimeInterval = [self timeIntervalFrom0000ByTimeString:strTmp];
    NSTimeInterval currentTimeInterval = [self timeIntervalFrom0000ByTimeString:[self currentTimeStrHHmm]];
    
    //如果 预约时间-当前时间 <= 30min && 当前时间－预约时间 >= 0,继续；否则return
    if (precontractTimeInterval-currentTimeInterval<=1800.00
        &&
        precontractTimeInterval-currentTimeInterval>=0)
    {
        ;
    }
    else
    {
        return;
    }
    
    xingCanCell.backgroundColor = [UIColor yellowColor];
    
    //    for (int i = 0; i<=5; i++)
    //    {
    //        ((UILabel *)[xingCanCell viewWithTag:i]).textColor = [UIColor yellowColor];
    //    }
}

-(void)setUpMantenceDisByCell:(UITableViewCell *)xingCanCell inRow:(NSInteger)xingCanRow
{
    /*
     超过交车时间的红色底色显示
     距离交车时间10min的黄色底色显示
     */
    NSString *strCurrTime = [self currentTimeStryyyyMMDDHHmm];
    NSString *strDeliveryPlannedTime = [[_arrCurrentMaintenanceList objectAtIndex:xingCanRow] objectForKey:@"deliveryPlannedDate"];
    NSTimeInterval dTimeInterval = [self timeIntervalByFirstTimeStr:strDeliveryPlannedTime subcontractSecondTimeStr:strCurrTime];
    
    if (dTimeInterval < 0)
    {
        //        xingCanCell.backgroundColor = [UIColor redColor];
        
        for (int i = 0; i<=5; i++)
        {
            ((UILabel *)[xingCanCell viewWithTag:i]).textColor = [UIColor redColor];
        }
    }
    else if (dTimeInterval <= 60*10)
    {
        xingCanCell.backgroundColor = [UIColor yellowColor];
        
        //        for (int i = 0; i<=5; i++)
        //        {
        //            ((UILabel *)[xingCanCell viewWithTag:i]).textColor = [UIColor yellowColor];
        //        }
    }
}

-(void)setUpSettlementDisByCell:(UITableViewCell *)xingCanCell inRow:(NSInteger)xingCanRow
{
    /*
     超过交车时间的红色底色显示
     距离交车时间10min的黄色底色显示
     */
    NSString *strCurrTime = [self currentTimeStryyyyMMDDHHmm];
    NSString *strDeliveryPlannedTime = [[_arrCurrentSettlementList objectAtIndex:xingCanRow] objectForKey:@"deliveryPlannedDate"];
    NSTimeInterval dTimeInterval = [self timeIntervalByFirstTimeStr:strDeliveryPlannedTime subcontractSecondTimeStr:strCurrTime];
    
    if (dTimeInterval < 0)
    {
        //        xingCanCell.backgroundColor = [UIColor redColor];
        
        for (int i = 0; i<=5; i++)
        {
            ((UILabel *)[xingCanCell viewWithTag:i]).textColor = [UIColor redColor];
        }
    }
    else if (dTimeInterval <= 60*10)
    {
        xingCanCell.backgroundColor = [UIColor yellowColor];
        
        //        for (int i = 0; i<=5; i++)
        //        {
        //            ((UILabel *)[xingCanCell viewWithTag:i]).textColor = [UIColor yellowColor];
        //        }
    }
}

//得到一个 HH:mm 时间格式 的时间 距离 当天凌晨的间隔，单位 s
-(NSTimeInterval)timeIntervalFrom0000ByTimeString:(NSString *)timeStr
{
//    NSLog(@"%@",timeStr);
    
    NSRange range = [timeStr rangeOfString:@":"];
    NSString *hh = [timeStr substringToIndex:range.location];
    NSString *mm = [timeStr substringFromIndex:range.location+1];
    
    return ([hh doubleValue]*3600+[mm doubleValue]*60.0);
}

//得到当前时间的 HH:mm 时间格式 字符串
-(NSString *)currentTimeStrHHmm
{
    NSDateFormatter *dateFormat=[[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"HH:mm"];
    //当前时间
    NSDate *currentTime = [NSDate dateWithTimeIntervalSinceNow:0];
    return [dateFormat stringFromDate:currentTime];
}

//获得当前的时间，时间格式：yyyy-MM-dd HH:mm
-(NSString *)currentTimeStryyyyMMDDHHmm
{
    NSDateFormatter *dateFormat=[[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];
    //当前时间
    NSDate *currentTime = [NSDate dateWithTimeIntervalSinceNow:0];
    return [dateFormat stringFromDate:currentTime];
}

//返回时间差值，时间格式为 yyyy-MM-dd HH:mm
-(NSTimeInterval)timeIntervalByFirstTimeStr:(NSString *)timeStrFirstly subcontractSecondTimeStr:(NSString *)timeStrSecondly
{
    NSDateFormatter *dateFormat=[[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    NSDate *firstTime = [dateFormat dateFromString:timeStrFirstly];
    NSDate *secondTime = [dateFormat dateFromString:timeStrSecondly];
    
    return [firstTime timeIntervalSince1970]-[secondTime timeIntervalSince1970];
    
    return 0;
}

/*end of add by mm*/

#pragma mark - HeadViewdelegate
-(void)selectedWith:(HeadView *)view
{
    _currentRow = -1;
    if (view.open)
    {
        for(int i = 0;i<[_headViewDis count];i++)
        {
            HeadView *head = [_headViewDis objectAtIndex:i];
            head.open = NO;
        }
        
        [_tbView reloadData];
        return;
    }
    
    _currentSection = view.section;
    [self resetTableView];
}



#pragma mark - SettingViewDelegate
- (void)onTapCloseControlSettingView:(SettingView*)settingView {
    [_settingView removeFromSuperview];
}

//系统设置
- (IBAction)sysSettingAction:(UIButton *)sender {
    _settingView = [SettingViewController shareInstance].settingView;
    _settingView.delegate = self;
    [self.view addSubview:_settingView];

//    if (!contentCon) {
//        contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
//    }
//    contentCon.delegate = self;
//    contentCon.btnSender=nil;
//    
////    NSString *Version = [NSString stringWithFormat:@"当前系统:%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
//    
//    NSMutableDictionary *dicConfigTmp = [HelpClass getDicDataFromConfigFileFromDocumnetFolder];
//    NSString *Version = [NSString stringWithFormat:@"当前系统:V%@",[dicConfigTmp objectForKey:@"GHAC_AppVersion"]];
//    
//    contentCon.list = [NSArray arrayWithObjects:@"登陆注销",@"IP设置",@"检查更新",Version, nil];
//    
//    self.popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
//    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
//    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
//    [DDPopoverBackgroundView setArrowHeight:15.0];
//    //[DDPopoverBackgroundView setShadowEnabled:NO];//关闭箭头
//    [DDPopoverBackgroundView setContentInset:1.0];
//    
//    [self.popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
//    [self.popCon setPopoverContentSize:CGSizeMake(160, 160)];
//    
//    [self.popCon presentPopoverFromRect:CGRectMake(0, 15, 0, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
-(void)selectDelegate:(NSInteger)row btn:(UIButton *)btn{
    
    if (row==0) {
        //调用接口
        webService *web=[[webService alloc] init];
        web.methodName = LOGOUT;
        [web commonGetSharedRequest:LOGOUT wsparas:nil];
        
        [self performSelector:@selector(systemLogin) withObject:nil afterDelay:0.3f];
        
    }else if (row==1){
        
        AppDelegate *myApp = [[UIApplication sharedApplication] delegate];
        
        NSString *title = [NSString stringWithFormat:@"您当前的IP地址是：\n%@",myApp.currentIp];
        self.myAlertView=[[UIAlertView alloc] initWithTitle:title message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登入",nil];
        
        [self.myAlertView show];
        
    }else if (row==2){
//        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"当前系统为最新版本！"message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
//        [av show];
        
//        AppDelegate *myApp = [[UIApplication sharedApplication] delegate];
//        NSString* url = [NSString stringWithFormat:@"http://%@/paddata/%@/GHAC_AppVersion.txt", myApp.currentIp,APP_AND_SETUP_FILE_FOLDER_NAME_];
//        NetworkTask * task = [[NetworkTask alloc] initWithGetUrl:url getArgs:nil];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTaskSuccess:) name:NetworkTask_NotificationName_OnSuccess object:task];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTaskFail:) name:NetworkTask_NotificationName_OnFail object:task];
//        [[NetworkManager getInstance] startTaskAsync:task];
//        [[NetworkingViewController sharedController] showNetworkingWithTitle:@"设置中..." content:nil activiting:YES enableDismiss:NO];
    }
    
    [self.popCon dismissPopoverAnimated:YES];
    contentCon = nil;
    self.popCon = nil;
}

#pragma mark -
- (void)onTaskSuccess:(NSNotification*)notify {
    
    NetworkTask* task = notify.object;
    NSLog(@"%@",task.resultDict);
    NSString *serverVersionStr = [task.resultDict objectForKey:@"GHAC_AppVersion"];
    NSString *localVersionStr = [[HelpClass getDicDataFromConfigFileFromDocumnetFolder] objectForKey:@"GHAC_AppVersion"];
    if ([serverVersionStr doubleValue] > [localVersionStr doubleValue])
    {
        //更新系统
        AppDelegate *myApp = [[UIApplication sharedApplication] delegate];
        NSString *urlStr = [NSString stringWithFormat:@"itms-services://?action=download-manifest&url=http://%@/PadData/%@/HondaPro_2.plist",myApp.currentIp,APP_AND_SETUP_FILE_FOLDER_NAME_];
        //检测更新版本
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
    }
    
    else
    {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"当前系统为最新版本！"message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
        [av show];
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];

}

- (void)onTaskFail:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"当前系统为最新版本！"message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
    [av show];
}

-(void)logout:(NSNotification*)notification{
    
    
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:(NSData*) notification.object options:NSJSONReadingMutableLeaves error:Nil];
    
    //
    NSLog(@"logout=====%@",[theJson objectForKey:@"error_code"]);
    if ([[theJson objectForKey:@"error_code"] integerValue]!=0) {
        
        
        //弹出提示框
//        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
//                                                      message:[theJson objectForKey:@"error_msg"]
//                                                     delegate:nil
//                                            cancelButtonTitle:@"确定"
//                                            otherButtonTitles:nil];
//        [alert show];
    }else{
        
//        [self performSelector:@selector(systemLogin) withObject:nil afterDelay:0.3f];
    }
    
}
- (void)willPresentAlertView:(UIAlertView *)alertView

{
    
    CGRect frame = alertView.frame;
    
    if( alertView==self.myAlertView )
        
    {
        
        frame.origin.y -= 120;
        
        frame.size.height += 30;
        
        alertView.frame = frame;
        
        for( UIView * view in alertView.subviews )
            
        {
            
            if( ![view isKindOfClass:[UILabel class]] )
                
            {
                
                if (view.tag==1)
                    
                {
                    
                    CGRect btnFrame1 =CGRectMake(30, frame.size.height-60, 105, 40);
                    
                    view.frame = btnFrame1;
                    
                    
                    
                } else if  (view.tag==2){
                    
                    CGRect btnFrame2 =CGRectMake(142, frame.size.height-60, 105, 40);
                    
                    view.frame = btnFrame2;
                    
                }
                
            }
            
        }
        
        
        
        //加入自訂的label及UITextFiled
        
        UILabel *lblaccountName=[[UILabel alloc] initWithFrame:CGRectMake( 30, 70,40, 30 )];;
        
        lblaccountName.text=@"IP：";
        
        lblaccountName.backgroundColor=[UIColor clearColor];
        
        [lblaccountName setFont:[UIFont systemFontOfSize:17.0]];
        
        lblaccountName.textColor=[UIColor whiteColor];
        
        
        
        self.accoutName = [[UITextField alloc] initWithFrame: CGRectMake( 65, 70,180, 30 )];
        
        self.accoutName.placeholder = @"ip:";
        
        self.accoutName.borderStyle=UITextBorderStyleRoundedRect;
        
        
        [alertView addSubview:lblaccountName];
        
        [alertView addSubview:self.accoutName];
        
        
        
    }
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView==self.myAlertView) {
        
        if (buttonIndex==1) {
            
            
            AppDelegate *myApp = [[UIApplication sharedApplication] delegate];
            myApp.currentIp = self.accoutName.text;
            
            //            //写入文
            NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *realPath = [documentPath stringByAppendingPathComponent:@"Config.plist"];
            
            NSMutableDictionary *dictplist = [[NSMutableDictionary alloc ] init];
            //设置属性值
            [dictplist setObject:self.accoutName.text forKey:@"ip"];
            
            //写入文件
            [dictplist writeToFile:realPath atomically:YES];
            
            NSURL *url1 = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@/dMS/PAD",self.accoutName.text]];
            NSURLRequest *request = [NSURLRequest requestWithURL:url1 cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
            NSHTTPURLResponse *response;
            [NSURLConnection sendSynchronousRequest:request returningResponse: &response error: nil];
            if (response == nil) {
//                NSLog(@"没有网络");
                NSString *title = [NSString stringWithFormat:@"IP设置 \n您当前IP设置错误 请重新设置"];
                self.myAlertView=[[UIAlertView alloc] initWithTitle:title message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登入",nil];
                [self.myAlertView show];
            }
            else{
//                NSLog(@"网络是通的");
            }
        }
    }
}

//注册消息
-(void)addAllObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData:) name:@"QUERY_REPAIR_WORK_COUNT" object:Nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logout:) name:LOGOUT object:nil];
}

//移除消息
-(void)removeAllObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//跳转到服务接待的界面，带入车牌号
-(void)switchToServiceUIByPlateNumber:(NSString *)plateNumberStrXingCan
{
    ServiceHomeViewController *VCon = [[ServiceHomeViewController alloc] initWithNibName:@"ServiceHomeViewController" bundle:nil];
    VCon.plateNumber.text = plateNumberStrXingCan;
    
    VCon.fromWhere = @"from_work_board";
    [self.navigationController pushViewController:VCon animated:YES];
}

//跳转到预约查询的界面，带入车牌号
-(void)switchToPreContractUIByPlateNumber:(NSString *)plateNumberStrXingCan
{
    ManagementViewController *mnv = [[ManagementViewController alloc]initWithNibName:@"ManagementViewController" bundle:nil];
    mnv.cardtextfield.text = plateNumberStrXingCan;
    [self.navigationController pushViewController:mnv animated:YES];
}

//进入结算界面，带入车牌号
-(void)switchToSettlementUIByPlateNumber:(NSString *)plateNumberStrXingCan
{
    VehicleSettlementViewController *vsv = [[VehicleSettlementViewController alloc]initWithNibName:@"VehicleSettlementViewController" bundle:nil];
    vsv.carframe.text = plateNumberStrXingCan;
    [self.navigationController pushViewController:vsv animated:YES];
}

#pragma mark - 按钮的回调方法
-(void)BtnOnHeadViewPressed:(UIButton *)btn
{
    NSInteger nCurrSumTmp = 0;
    NSInteger nAllSumTmp = 0;
    NSString *strPreTmp = @"";
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    /*
     {"salerName":"4","salerID":"1884","tel":"","email":"","error_code":0,"error_msg":""}
     */
    
    if (btn == _button1ForWorkBoard)
    {
//        if (BTN_IS_CURR_PERSON_ == _bFlagBtn1ForWorkBoard)
//        {
//            _bFlagBtn1ForWorkBoard = BTN_IS_ALL_PERSON_;
//            strPreTmp = @"全部";
//        }
//        else
//        {
//            _bFlagBtn1ForWorkBoard = BTN_IS_CURR_PERSON_;
//            //            strPreTmp = @"登录者";
//            strPreTmp = [modelIns.dicSalerInfo objectForKey:@"salerName"];
//        }
//        //[self setUpArrValByBtnState];
//        nCurrSumTmp = [self currentPersonSumBySection:0];
//        nAllSumTmp = [self allPersonSumBySection:0];
        
        [self switchToPreContractUIByPlateNumber:nil];

    }
    else if (btn == _button2ForWorkBoard)
    {
//        if (BTN_IS_CURR_PERSON_ == _bFlagBtn2ForWorkBoard)
//        {
//            _bFlagBtn2ForWorkBoard = BTN_IS_ALL_PERSON_;
//            strPreTmp = @"全部";
//        }
//        else
//        {
//            _bFlagBtn2ForWorkBoard = BTN_IS_CURR_PERSON_;
//            //            strPreTmp = @"登录者";
//            strPreTmp = [modelIns.dicSalerInfo objectForKey:@"salerName"];
//        }
//        //[self setUpArrValByBtnState];
//        nCurrSumTmp = [self currentPersonSumBySection:1];
//        nAllSumTmp = [self allPersonSumBySection:1];
        
        [self switchToServiceUIByPlateNumber:nil];
    }
    else if (btn == _button3ForWorkBoard)
    {
//        if (BTN_IS_CURR_PERSON_ == _bFlagBtn3ForWorkBoard)
//        {
//            _bFlagBtn3ForWorkBoard = BTN_IS_ALL_PERSON_;
//            strPreTmp = @"全部";
//        }
//        else
//        {
//            _bFlagBtn3ForWorkBoard = BTN_IS_CURR_PERSON_;
//            //            strPreTmp = @"登录者";
//            strPreTmp = [modelIns.dicSalerInfo objectForKey:@"salerName"];
//        }
//        //[self setUpArrValByBtnState];
//        nCurrSumTmp = [self currentPersonSumBySection:2];
//        nAllSumTmp = [self allPersonSumBySection:2];
        
        [self switchToSettlementUIByPlateNumber:nil];
    }
    
    //设置按钮的显示字符串
    //[btn setTitle:[NSString stringWithFormat:@"%@(%i/%i)",strPreTmp,nCurrSumTmp,nAllSumTmp] forState:UIControlStateNormal];
    
    //重新给数组赋值
    //[self setUpArrValByBtnState];
    
    //刷新工作台表单
    //[_tbView reloadData];
}

//根据按钮的状态 给数组赋值
-(void)setUpArrValByBtnState
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    //预约
    if (BTN_IS_CURR_PERSON_ == _bFlagBtn1ForWorkBoard)
    {
        _arrCurrentPrecontractList = [NSMutableArray array];
        for (int i = 0; i<[modelIns.precontractList count]; i++)
        {
            NSString *strIdTmp = [[modelIns.precontractList objectAtIndex:i] objectForKey:@"evaluatorPersonId"];
            if ([strIdTmp isEqualToString:modelIns.strCurrentSalerId])
            {
                [_arrCurrentPrecontractList addObject:[modelIns.precontractList objectAtIndex:i]];
            }
        }
    }
    else
    {
        _arrCurrentPrecontractList = [NSMutableArray arrayWithArray:modelIns.precontractList];
    }
    
    //维修中
    if (BTN_IS_CURR_PERSON_ == _bFlagBtn2ForWorkBoard)
    {
        _arrCurrentMaintenanceList = [NSMutableArray array];
        for (int i = 0; i<[modelIns.maintenanceList count]; i++)
        {
            NSString *strIdTmp = [[modelIns.maintenanceList objectAtIndex:i] objectForKey:@"evaluatorPersonId"];
            if ([strIdTmp isEqualToString:modelIns.strCurrentSalerId])
            {
                [_arrCurrentMaintenanceList addObject:[modelIns.maintenanceList objectAtIndex:i]];
            }
        }
    }
    else
    {
        _arrCurrentMaintenanceList = [NSMutableArray arrayWithArray:modelIns.maintenanceList];
    }
    
    //待结算
    if (BTN_IS_CURR_PERSON_ == _bFlagBtn3ForWorkBoard)
    {
        _arrCurrentSettlementList = [NSMutableArray array];
        for (int i = 0; i<[modelIns.settlementList count]; i++)
        {
            NSString *strIdTmp = [[modelIns.settlementList objectAtIndex:i] objectForKey:@"evaluatorPersonId"];
            if ([strIdTmp isEqualToString:modelIns.strCurrentSalerId])
            {
                [_arrCurrentSettlementList addObject:[modelIns.settlementList objectAtIndex:i]];
            }
        }
    }
    else
    {
        _arrCurrentSettlementList = [NSMutableArray arrayWithArray:modelIns.settlementList];
    }
}

//当前估价人的数量
-(NSInteger)currentPersonSumBySection:(NSInteger)sectionXingCan
{
    NSInteger nSum = 0;
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    switch (sectionXingCan)
    {
        case 0:
            for (int i = 0; i<[modelIns.precontractList count]; i++)
            {
                NSString *strIdTmp = [[modelIns.precontractList objectAtIndex:i] objectForKey:@"evaluatorPersonId"];
                if ([strIdTmp isEqualToString:modelIns.strCurrentSalerId])
                {
                    nSum ++;
                }
            }
            break;
        case 1:
            for (int i = 0; i<[modelIns.maintenanceList count]; i++)
            {
                NSString *strIdTmp = [[modelIns.maintenanceList objectAtIndex:i] objectForKey:@"evaluatorPersonId"];
                if ([strIdTmp isEqualToString:modelIns.strCurrentSalerId])
                {
                    nSum ++;
                }
            }
            break;
        case 2:
            for (int i = 0; i<[modelIns.settlementList count]; i++)
            {
                NSString *strIdTmp = [[modelIns.settlementList objectAtIndex:i] objectForKey:@"evaluatorPersonId"];
                if ([strIdTmp isEqualToString:modelIns.strCurrentSalerId])
                {
                    nSum ++;
                }
            }
            break;
            
        default:
            break;
    }
    return nSum;
}

//全部的数量
-(NSInteger)allPersonSumBySection:(NSInteger)sectionXingCan
{
    NSInteger nSum = 0;
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    switch (sectionXingCan)
    {
        case 0:
            nSum = [modelIns.precontractList count];
            break;
        case 1:
            nSum = [modelIns.maintenanceList count];
            break;
        case 2:
            nSum = [modelIns.settlementList count];
            break;
            
        default:
            break;
    }
    return nSum;
}

//根据按钮的状态设置按钮的显示字符串
-(void)setUpBtnDisStr
{
    NSInteger nCurrSumTmp = 0;
    NSInteger nAllSumTmp = 0;
    NSString *strPreTmp = @"";
    
    if (BTN_IS_CURR_PERSON_ == _bFlagBtn1ForWorkBoard)
    {
        strPreTmp = @"登录者";
    }
    else
    {
        strPreTmp = @"全部";
    }
    nCurrSumTmp = [self currentPersonSumBySection:0];
    nAllSumTmp = [self allPersonSumBySection:0];
    [_button1ForWorkBoard setTitle:[NSString stringWithFormat:@"%@(%i/%i)",strPreTmp,nCurrSumTmp,nAllSumTmp] forState:UIControlStateNormal];
    
    if (BTN_IS_CURR_PERSON_ == _bFlagBtn2ForWorkBoard)
    {
        strPreTmp = @"登录者";
    }
    else
    {
        strPreTmp = @"全部";
    }
    nCurrSumTmp = [self currentPersonSumBySection:1];
    nAllSumTmp = [self allPersonSumBySection:1];
    [_button2ForWorkBoard setTitle:[NSString stringWithFormat:@"%@(%i/%i)",strPreTmp,nCurrSumTmp,nAllSumTmp] forState:UIControlStateNormal];
    
    if (BTN_IS_CURR_PERSON_ == _bFlagBtn3ForWorkBoard)
    {
        strPreTmp = @"登录者";
    }
    else
    {
        strPreTmp = @"全部";
    }
    nCurrSumTmp = [self currentPersonSumBySection:2];
    nAllSumTmp = [self allPersonSumBySection:2];
    [_button3ForWorkBoard setTitle:[NSString stringWithFormat:@"%@(%i/%i)",strPreTmp,nCurrSumTmp,nAllSumTmp] forState:UIControlStateNormal];
}




- (IBAction)onTapElearningButton:(UIButton *)sender {
    NSURL * myURL_APP_A = [NSURL URLWithString:@"cloudStudy://com.tbc.cloudStudy"];//myapp为目标App的key
    if ([[UIApplication sharedApplication] canOpenURL:myURL_APP_A]) {
        [[UIApplication sharedApplication] openURL:myURL_APP_A];
    }
}
// 走进广汽
//- (IBAction)onTapEnterShow:(id)sender {
//
//    EnterHondaViewController * controller = [[EnterHondaViewController alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
//
//
//    //[self.navigationController pushViewController:controller animated:YES];
//
//    AddServiceViewController* viewController = [[AddServiceViewController alloc] initWithNibName:@"AddServiceViewController" bundle:nil];
//    viewController.detailType = TypeZouJin;
//    [self.navigationController pushViewController:viewController animated:YES];
//
//}
// 本店优势
//- (IBAction)onTapStoreShow:(id)sender {
//
//    StoreViewController * controller = [[StoreViewController alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
//    //[self.navigationController pushViewController:controller animated:YES];
//
//    AddServiceViewController* viewController = [[AddServiceViewController alloc] initWithNibName:@"AddServiceViewController" bundle:nil];
//    viewController.detailType = Type4S;
//    [self.navigationController pushViewController:viewController animated:YES];
//
//    [[ConfigCodeHelper shareInstance] updataPadDataSourceByKey:@"version"];
//
//}


//广汽科技
//- (IBAction)onTapTechnologyButton:(id)sender
//{
//    TechnologyViewController * homecontroller = [[TechnologyViewController alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
//    //[self.navigationController pushViewController:homecontroller animated:YES];
//    AddServiceViewController* viewController = [[AddServiceViewController alloc] initWithNibName:@"AddServiceViewController" bundle:nil];
//    viewController.detailType = TypeKeJi;
//    [self.navigationController pushViewController:viewController animated:YES];
//}

//品牌故事
//- (IBAction)onTapBrandStoryButton:(id)sender
//{
//
//    BrandViewController * brandController = [[BrandViewController alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
//    //[self.navigationController pushViewController:brandController animated:YES];
//
//    AddServiceViewController* viewController = [[AddServiceViewController alloc] initWithNibName:@"AddServiceViewController" bundle:nil];
//    viewController.detailType = TypePinPai;
//    [self.navigationController pushViewController:viewController animated:YES];
//}

@end
